package com.qf.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.Course;
import com.qf.pojo.Subject;
import com.qf.service.CourseService;
import com.qf.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@Controller
@RequestMapping("course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private SubjectService subjectService;

    //根据课程信息展示信息
    @RequestMapping("course/{id}")
    public String findSubjectById(@PathVariable(name = "id") Integer id, Model model) {

        Subject subject = subjectService.findSubjectById(id);
        List<Subject> subjectList = subjectService.findAllSubject();

        model.addAttribute("subject", subject);
        model.addAttribute("subjectList", subjectList);
        return "before/course.jsp";
    }

    //分页展示课程信息
    @RequestMapping("showCourseList")
    public String showCourseList(Model model,
                                 @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                 @RequestParam(required = false, defaultValue = "10") Integer pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        List<Course> courseList = courseService.findAll();

        PageInfo<Course> pageInfo = new PageInfo<>(courseList);

        model.addAttribute("page", pageInfo);

        return "behind/courseList.jsp";
    }

    //跳转到添加课程界面
    @RequestMapping("addCourse")
    public String addCourse() {
        return "behind/addCourse.jsp";
    }

    //添加/修改课程
    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(Course course) {
        if (course.getId() == null) {
            courseService.addCourse(course);
        } else {
            courseService.update(course);
        }

        return "redirect:showCourseList";
    }

    //删除课程
    @RequestMapping("courseDel")
    @ResponseBody
    public String courseDel(Integer id) {
        courseService.deleteCourse(id);

        Course course = courseService.findCourseById(id);

        if (course == null) {
            return "success";
        } else {
            return "false";
        }
    }
}
